package com.h2cloud.JUCTest.patten;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j(topic = "c.TestGuardedObject")
public class TestGuardedObject {
	public static void main(String[] args) {
		GuardedObject guardObject = new GuardedObject();

		new Thread(() -> {
			log.debug("等待结果");
			List<String> results = (List<String>) guardObject.get();
			log.debug("获取结果完毕,结果大小为：{}", results.size());

		}, "t1").start();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		new Thread(() -> {
			log.debug("执行下载");
			List<String> downloaderData = null;
			try {
				downloaderData = Downloader.download();
				guardObject.complete(downloaderData);
				log.debug("下载结束");
			} catch (IOException e) {
				e.printStackTrace();
			}

		}, "t2").start();
	}

}

class GuardedObject {

	private Object response;
	private final Object lock = new Object();

	public Object get() {
		synchronized (lock) {
			// 条件不满足则等待
			while (response == null) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return response;
		}
	}

	public void complete(Object response) {
		synchronized (lock) {
			// 条件满足，通知等待线程
			this.response = response;
			lock.notifyAll();
		}
	}
}
